<!-- 实习生证明模板新增、修改 -->
<template>
  <PageHeaderNew :title="title" :breadCrumb="breadCrumb" :showBack="true">
    <template #buts>
      <a-button type="primary" @click="save()">保存</a-button>
    </template>
  </PageHeaderNew>
  <div class="index">
    <a-form
      ref="formRef"
      direction="vertical"
      :model="internshipTemplateDetail.info"
      :rules="rules"
      auto-label-width
    >
      <a-form-item field="name" label="模板名称">
        <a-input
          placeholder="模板名称"
          v-model="internshipTemplateDetail.info.name"
        />
      </a-form-item>
      <a-form-item field="explain" label="模板说明">
        <a-textarea
          placeholder="模板说明"
          v-model="internshipTemplateDetail.info.remark"
          :auto-size="{
            minRows: 3
          }"
          :max-length="300"
          show-word-limit
        />
      </a-form-item>
      <a-form-item field="type" label="模板尺寸">
        <a-space direction="vertical" size="large">
          <a-radio-group
            :default-value="1"
            v-model="internshipTemplateDetail.info.direction"
          >
            <a-radio :value="1">A4 纵版</a-radio>
            <a-radio :value="2">A4 横版</a-radio>
          </a-radio-group>
        </a-space>
      </a-form-item>
      <a-form-item field="content" label="模板内容">
        <a-space direction="vertical">
          <!-- <RichTextCertificate
            v-model:content="internshipTemplateDetail.info.text"
          ></RichTextCertificate> -->
          <a-space wrap>
            <a-button
              v-for="(item, index) in controlList"
              :key="index"
              @click="inputLabel(item, index)"
              >#{{ item.cnName }}#</a-button
            >
          </a-space>
          <RichTextNew
            v-model:content="internshipTemplateDetail.info.text"
            ref="rich"
          ></RichTextNew>
        </a-space>
      </a-form-item>
      <!-- <a-form-item field="file" label="附件">
        <a-button @click="upload()">上传文件</a-button>
      </a-form-item> -->
    </a-form>
  </div>
</template>
<script setup lang="ts">
import * as apiVariation from '@/apis/human/base/variationManager';
import { TEditInternshipTemplate } from '@/apis/human/base/variationManager/type';
import {
  GetInternshipCertificateTemplate,
  PostInternshipCertificateTemplate,
  PutInternshipCertificateTemplate,
  PutInternshipCertificateTemplateState,
  DelInternshipCertificateTemplate
} from '@/apis/management/human/baseSetting/internshipSetting';
import { GetBusinessModalData } from '@/apis/controltotal';
import { useRoute, useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import RichTextCertificate from '@/components/RichTextCertificate/index.vue';
import { changeControlData } from '@/utils/control';
const route = useRoute();
const router = useRouter();
let details = route.query;

let title = details.id ? '编辑实习证明模板' : '新增实习证明模板';
let breadCrumb: string[] = ['人事', '异动管理', `${title}`];
const formRef = ref();
const rules = {
  name: {
    required: true,
    message: '请填写名称',
    trigger: "['change', 'input', 'blur']"
  }
};
let codes: any = []; // 储存当前选择的控件
const internshipTemplateDetail = reactive<{ info: any }>({
  info: {
    name: '', // 模板名称
    remark: '', // 模板描述
    required: 2, // 是否默认 1是 2否
    direction: 1, //默认1 模板页面方向 1：A4纵版 2：A4横版
    text: '', // 模板内容
    codes: '' // 控件编码数组，逗号隔开
  }
});
// tab选项初始数据
const controlList: any = ref();
// 富文本ref
const rich = ref();
// 新增tab
const inputLabel = (item: any, ind: number) => {
  const arr = codes;
  if (arr?.length !== 0) {
    if (
      !arr?.some((ele: any) => ele.ctlCode === controlList.value[ind].ctlCode)
    ) {
      arr?.push(controlList.value[ind]);
    }
  } else {
    arr?.push(controlList.value[ind]);
  }

  const tag = `&nbsp;<span style="text-decoration: underline; color: #3598db; font-size: 12pt;">#${item.cnName}#</span>&nbsp;`;
  nextTick(() => {
    rich.value.insertContent(tag);
  });
};

// 编辑情况下需要转换成数字类型的属性
const NumberTypeEnum = ['id', 'required', 'direction'];
//获取实习证明模板详情
const getData = async () => {
  internshipTemplateDetail.info = {
    ...details
  };
  codes = [];
  const currCodes = internshipTemplateDetail.info.codes.split(',');

  for (let i in internshipTemplateDetail.info) {
    if (NumberTypeEnum.includes(i))
      internshipTemplateDetail.info[i] = +internshipTemplateDetail.info[i];
  }
  controlList.value.forEach((item: any) => {
    let regexp = new RegExp(`#${item.ctlCode}#`, 'g');
    internshipTemplateDetail.info.text =
      internshipTemplateDetail.info.text.replace(regexp, `#${item.cnName}#`);
    if (currCodes.includes(item.ctlCode)) codes.push(item);
  });
};

const save = async () => {
  // 验证表单
  if (await formRef.value.validate()) return;
  let {
    info: { id }
  } = internshipTemplateDetail;
  let msg = '新增成功';
  // 新增
  if (!id) {
    const arr: any = [];
    codes.forEach((item: any) => {
      arr.push(item.ctlCode);
      let regexp = new RegExp(`#${item.cnName}#`, 'g');
      internshipTemplateDetail.info.text =
        internshipTemplateDetail.info.text.replace(regexp, `#${item.ctlCode}#`);
    });
    internshipTemplateDetail.info.codes = arr.join(',');
    console.log(internshipTemplateDetail.info);

    await PostInternshipCertificateTemplate(internshipTemplateDetail.info);
  } else {
    // 编辑
    const arr: any = [];
    codes.forEach((item: any) => {
      arr.push(item.ctlCode);
      let regexp = new RegExp(`#${item.cnName}#`, 'g');
      internshipTemplateDetail.info.text =
        internshipTemplateDetail.info.text.replace(regexp, `#${item.ctlCode}#`);
    });

    // controlList.value.forEach((item: any) => {
    //   let regexp = new RegExp(`#${item.cnName}#`, 'g');
    //   internshipTemplateDetail.info.text =
    //     internshipTemplateDetail.info.text.replace(regexp, `#${item.ctlCode}#`);
    // });
    internshipTemplateDetail.info.codes = arr.join(',');

    await PutInternshipCertificateTemplate(internshipTemplateDetail.info);

    msg = '编辑成功';
  }
  Message.success(msg);
  router.back();
};
const upload = () => {
  Message.warning('敬请期待~');
};

const init = async () => {
  // 获取控件总集数据
  const { funcCtlInfos }: any = await GetBusinessModalData({
    funcCode: 'SER_FUNC9B158E4240DE49979E62895D0AEF9080'
  });

  controlList.value = changeControlData(funcCtlInfos, 'tableHead');

  internshipTemplateDetail.info.id = route.query.id
    ? Number(route.query.id)
    : void 0;
  if (!internshipTemplateDetail.info.id) return;
  getData();
};
init();
</script>
<style lang="less" scoped>
.index {
  padding: 10px 20px;
}
</style>
